<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue';
import { 
  LeftOutlined, 
  RightOutlined,
  MobileOutlined,
  TabletOutlined,
  DesktopOutlined,
  EyeOutlined,
  DownloadOutlined,
  CodeOutlined,
  UndoOutlined,
  RedoOutlined,
  SettingOutlined
} from '@ant-design/icons-vue';
import LeftPanel from './com/LeftPanel.vue';
import DraggableItem from './com/DraggableItem.vue';
import { useEditorStore } from '@/stores/editor';
import PropertyPanel from './com/PropertyPanel.vue';
import ThemeSettings from './com/ThemeSettings.vue';
import CodePreview from './com/CodePreview.vue';
import AlignmentGuides from './com/AlignmentGuides.vue';
import ComponentGroup from './com/ComponentGroup.vue';
import PreviewPage from './com/PreviewPage.vue';
import AlignmentToolbar from './com/AlignmentToolbar.vue';
import RightPanel from './com/RightPanel.vue';

const editorStore = useEditorStore();

const isLeftPanelCollapsed = ref(false);
const isRightPanelCollapsed = ref(false);

const deviceMode = ref('desktop');
const mainContentWidth = computed(() => {
  switch(deviceMode.value) {
    case 'mobile': return '375px';
    case 'tablet': return '768px';
    case 'desktop': return '100%';
    default: return '100%';
  }
});

// 只显示根级组件（没有 parentId 的组件）
const rootComponents = computed(() => 
  editorStore.canvasComponents.filter(comp => !comp.parentId)
);

const onDrop = (event: DragEvent) => {
  const configData = event.dataTransfer?.getData('json/plain');
  if (!configData) return;
  
  try {
    const componentConfig = JSON.parse(configData);
    if (componentConfig && componentConfig.field) {
      editorStore.addComponent(componentConfig);
    }
  } catch (error) {
    console.error('Error adding component:', error);
  }
};

const onDragOver = (event: DragEvent) => {
  event.preventDefault();
};

// 点击内容区域时取消组件选中
const handleContentClick = () => {
  editorStore.selectComponent(null);
};

const themeSettingsVisible = ref(false);
const codePreviewVisible = ref(false);

// 添加拖拽状态
const draggingRect = ref<DOMRect | null>(null);

// 监听拖拽组件的位置变化
watch(() => editorStore.draggingId, (newId) => {
  if (!newId) {
    draggingRect.value = null;
  }
});

// 添加快捷键处理
const handleKeyDown = (event: KeyboardEvent) => {
  // 如果当前焦点在输入框中，不处理快捷键
  if (event.target instanceof HTMLInputElement || 
      event.target instanceof HTMLTextAreaElement) {
    return;
  }

  // Ctrl/Cmd + Z = 撤销
  if ((event.ctrlKey || event.metaKey) && event.key === 'z' && !event.shiftKey) {
    event.preventDefault();
    editorStore.undo();
  }
  
  // Ctrl/Cmd + Shift + Z = 重做
  if ((event.ctrlKey || event.metaKey) && event.key === 'z' && event.shiftKey) {
    event.preventDefault();
    editorStore.redo();
  }
  
  // Ctrl/Cmd + C = 复制选中组件
  if ((event.ctrlKey || event.metaKey) && event.key === 'c') {
    event.preventDefault();
    if (editorStore.selectedComponentId) {
      editorStore.duplicateComponent(editorStore.selectedComponentId);
    }
  }
  
  // Delete/Backspace = 删除选中组件
  if (event.key === 'Delete' || event.key === 'Backspace') {
    if (editorStore.selectedComponentId) {
      event.preventDefault();
      editorStore.deleteComponent(editorStore.selectedComponentId);
    }
  }
  
  // Ctrl/Cmd + G = 组合选中的组件
  if ((event.ctrlKey || event.metaKey) && event.key === 'g') {
    event.preventDefault();
    const selectedIds = editorStore.getSelectedComponentIds();
    if (selectedIds.length > 1) {
      editorStore.groupComponents(selectedIds);
    }
  }
  
  // Ctrl/Cmd + Shift + G = 解组
  if ((event.ctrlKey || event.metaKey) && event.shiftKey && event.key === 'g') {
    event.preventDefault();
    if (editorStore.selectedComponentId) {
      editorStore.ungroupComponents(editorStore.selectedComponentId);
    }
  }
};

// 在组件挂载时添加事件监听
onMounted(() => {
  window.addEventListener('keydown', handleKeyDown);
});

// 在组件卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener('keydown', handleKeyDown);
});

// 添加预览状态
const previewVisible = ref(false);

const downloadConfig = () => {
  const config = JSON.stringify(editorStore.canvasComponents, null, 2);
  const blob = new Blob([config], { type: 'application/json' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = 'canvas-config.json';
  a.click();
  URL.revokeObjectURL(url);
};

const toggleLeftPanel = () => {
  isLeftPanelCollapsed.value = !isLeftPanelCollapsed.value;
};

const toggleRightPanel = () => {
  isRightPanelCollapsed.value = !isRightPanelCollapsed.value;
};
</script>
<template>
    <div class="editor-container">
        <!-- 顶部工具栏 -->
        <div class="toolbar">
            <div class="left-tools">
                <a-space>
                    <a-button-group>
                        <a-button 
                            :type="deviceMode === 'desktop' ? 'primary' : 'default'"
                            @click="deviceMode = 'desktop'"
                        >
                            <template #icon><DesktopOutlined /></template>
                        </a-button>
                        <a-button 
                            :type="deviceMode === 'tablet' ? 'primary' : 'default'"
                            @click="deviceMode = 'tablet'"
                        >
                            <template #icon><TabletOutlined /></template>
                        </a-button>
                        <a-button 
                            :type="deviceMode === 'mobile' ? 'primary' : 'default'"
                            @click="deviceMode = 'mobile'"
                        >
                            <template #icon><MobileOutlined /></template>
                        </a-button>
                    </a-button-group>

                    <a-button-group>
                        <a-button :disabled="!editorStore.canUndo">
                            <template #icon><UndoOutlined /></template>
                        </a-button>
                        <a-button :disabled="!editorStore.canRedo">
                            <template #icon><RedoOutlined /></template>
                        </a-button>
                    </a-button-group>
                </a-space>
            </div>

            <div class="right-tools">
                <a-space>
                    <a-button @click="codePreviewVisible = true">
                        <template #icon><CodeOutlined /></template>
                        查看代码
                    </a-button>
                    <a-button @click="previewVisible = true">
                        <template #icon><EyeOutlined /></template>
                        预览
                    </a-button>
                    <a-button @click="downloadConfig">
                        <template #icon><DownloadOutlined /></template>
                        下载配置
                    </a-button>
                    <a-button @click="themeSettingsVisible = true">
                        <template #icon><SettingOutlined /></template>
                        主题设置
                    </a-button>
                </a-space>
            </div>
        </div>

        <div class="editor-content">
            <!-- 左侧组件区域 -->
            <div class="left-panel-wrapper">
                <div class="collapse-button" @click="toggleLeftPanel">
                    <component :is="isLeftPanelCollapsed ? RightOutlined : LeftOutlined" />
                </div>
                <div class="left-panel" :class="{ 'collapsed': isLeftPanelCollapsed }">
                    <LeftPanel />
                </div>
            </div>

            <!-- 中间内容区域 -->
            <div class="main-content-wrapper">
                <div 
                    class="main-content" 
                    @drop.prevent="onDrop"
                    @dragover.prevent
                >
                    <AlignmentGuides :dragging-rect="draggingRect" />
                    <h3>内容区</h3>
                    <div @click="handleContentClick">
                        <DraggableItem
                            v-for="component in rootComponents"
                            :key="component.id"
                            :id="component.id"
                            :configData="component.configData"
                        />
                    </div>
                </div>
            </div>

            <!-- 右侧属性配置区域 -->
            <div class="right-panel-wrapper">
                <div class="right-panel">
                    <RightPanel />
                </div>
                <div class="collapse-button" @click="toggleRightPanel">
                    <component :is="isRightPanelCollapsed ? LeftOutlined : RightOutlined" />
                </div>
            </div>
        </div>

        <!-- 添加主题设置对话框 -->
        <ThemeSettings
            v-model:visible="themeSettingsVisible"
            @ok="() => {}"
            @cancel="() => {}"
        />

        <!-- 添加代码预览对话框 -->
        <CodePreview v-model:visible="codePreviewVisible" />

        <!-- 添加预览页面 -->
        <PreviewPage v-if="previewVisible" v-model:visible="previewVisible" />

        <AlignmentToolbar />
    </div>
</template>

<style lang="less" scoped>
.editor-container {
    height: 100vh;
    display: flex;
    flex-direction: column;
    background-color: #f0f2f5;
}

.toolbar {
    height: 48px;
    background-color: #fff;
    border-bottom: 1px solid #e8e8e8;
    padding: 0 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.editor-content {
    flex: 1;
    display: flex;
    overflow: hidden;
}

.main-content-wrapper {
    flex: 1;
    overflow: hidden;
    padding: 20px;
    background: #f0f2f5;
}

.main-content {
    height: 100%;
    overflow-y: auto;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    padding: 24px;
    min-height: 300px;
}

.left-panel-wrapper {
    position: relative;
    display: flex;
    background: #fff;
    transition: all 0.3s;

    .collapse-button {
        position: absolute;
        right: -16px;
        top: 50%;
        transform: translateY(-50%);
        width: 16px;
        height: 64px;
        background: #fff;
        border-radius: 0 4px 4px 0;
        box-shadow: 2px 0 8px rgba(0, 0, 0, 0.15);
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        z-index: 1;

        &:hover {
            color: #1890ff;
        }
    }

    .left-panel {
        width: 300px;
        transition: all 0.3s;
        display: flex;
        flex-direction: column;
        box-shadow: 2px 0 8px rgba(0, 0, 0, 0.15);
        
        &.collapsed {
            width: 0;
            overflow: hidden;
        }

        :deep(.ant-collapse) {
            flex: 1;
            overflow-y: auto;
            border: none;
            background: transparent;
        }

        :deep(.ant-collapse-item) {
            border-bottom: 1px solid #f0f0f0;
        }

        :deep(.ant-collapse-header) {
            padding: 12px 16px !important;
        }

        :deep(.ant-collapse-content-box) {
            padding: 0 8px 8px !important;
        }
    }
}

.right-panel-wrapper {
    position: relative;
    display: flex;
    background: #fff;
    transition: all 0.3s;

    .collapse-button {
        position: absolute;
        left: -16px;
        top: 50%;
        transform: translateY(-50%);
        width: 16px;
        height: 64px;
        background: #fff;
        border-radius: 4px 0 0 4px;
        box-shadow: -2px 0 8px rgba(0, 0, 0, 0.15);
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        z-index: 1;

        &:hover {
            color: #1890ff;
        }
    }

    .right-panel {
        width: 300px;
        transition: all 0.3s;
        overflow-y: auto;
        box-shadow: -2px 0 8px rgba(0, 0, 0, 0.15);
        
        &.collapsed {
            width: 0;
            overflow: hidden;
        }
    }
}

/* 添加全局CSS变量 */
:root {
  --primary-color: #1890ff;
  --border-radius: 4px;
  --font-size: 14px;
}

/* 使用CSS变量 */
.editor-container {
  font-size: var(--font-size);
}

.panel {
  border-radius: var(--border-radius);
}

.a-button-primary {
  background-color: var(--primary-color);
}
</style>